import 'dart:async';

import 'package:flutter/material.dart';
import 'package:stage_app/constants/color_constant.dart';

class CaptchaButton extends StatefulWidget {
  /// 倒计时的秒数，默认60秒。
  final int countdown;
  final Color bgColor;
  final Color textColor;
  final Function getVCode;

  const CaptchaButton({Key key, this.countdown = 60, this.getVCode, this.bgColor = ColorConstant.app_main,this.textColor})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _CaptchaButtonState();
}

class _CaptchaButtonState extends State<CaptchaButton> {
  bool _isAvailableGetVCode = true; //是否可以获取验证码，默认为`false`
  String _verifyStr = '验证码';

  // 倒计时的计时器。
  Timer _timer;

  // 当前倒计时的秒数。
  int _seconds;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _seconds = widget.countdown;
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
        width: 100,
        height: 24,
//        decoration: new BoxDecoration(
//            border: new Border.all(
//                color: _isAvailableGetVCode
//                    ? Color(0xFF689EFD)
//                    : Color(0xFFCCCCCC),
//                width: 1)),
        child: FlatButton(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12) //设置圆角
          ),
          color: ColorConstant.app_main,
          disabledColor: Color(0xFFCCCCCC),
          disabledTextColor: Color(0xFFCCCCCC),
          onPressed: _seconds == widget.countdown
              ? () {
                  _startTimer();
                  widget.getVCode();
                }
              : null,
          child: Text(
            '$_verifyStr',
            maxLines: 1,
            style: TextStyle(
              fontSize: 12,
              color:
                  _isAvailableGetVCode ? Colors.white : Color(0xFFFFFFFF),
            ),
          ),
        ));
  }

  void _startTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _seconds--;
      _isAvailableGetVCode = false;
      _verifyStr = '已发送(${_seconds}s)';
      if (_seconds == 0) {
        _verifyStr = '重新获取';
        _isAvailableGetVCode = true;
        _seconds = widget.countdown;
        _cancelTimer();
      }
      setState(() {});
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }
}
